package com.jlpay.openapi.demo.ledger.merchconf;

import com.jlpay.open.jlpay.sdk.java.model.ledger.request.MerchFileUploadRequest;
import com.jlpay.open.jlpay.sdk.java.model.ledger.response.MerchFileUploadResponse;
import com.jlpay.open.jlpay.sdk.java.utils.json.JsonUtils;
import com.jlpay.openapi.demo.JlpayOpenApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.Base64;

/**
 *
 * @author dengwenning
 * @since 2024/8/30
 **/
public class MerchFileUploadService {

    private static final Logger LOGGER = LoggerFactory.getLogger(MerchFileUploadService.class);

    public static void main(String[] args) {
        MerchFileUploadRequest merchFileUploadRequest = buildMerchFileUploadRequest();
        MerchFileUploadResponse merchFileUploadResponse = JlpayOpenApiService.openMerchService()
                .post(merchFileUploadRequest, MerchFileUploadResponse.class);
        LOGGER.info("分账配置附件上传响应:{}", JsonUtils.toString(merchFileUploadResponse));
    }

    private static MerchFileUploadRequest buildMerchFileUploadRequest() {
        MerchFileUploadRequest merchFileUploadRequest = new MerchFileUploadRequest();
        merchFileUploadRequest.setOrgCode("50720711");
        String path = new File("test.png").getAbsolutePath();
        String base64File = fileToBase64(path);
        // 传入base64
        merchFileUploadRequest.setFileBase64("data:image/png;base64," + base64File);
        return merchFileUploadRequest;
    }

    /**
     * 文件流转换成Base64
     */
    public static String fileToBase64(String path) {
        String base64 = null;
        InputStream in = null;
        try {
            File file = new File(path);
            in = Files.newInputStream(file.toPath());
            byte[] bytes = new byte[(int) file.length()];
            in.read(bytes);
            base64 = Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;
    }

}
